from flask import jsonify, request, g
from . import repair
from .authentication import auth
from ..models import *
from .. import db
from .errors import unauthorized

@repair.route('/')
def index():
    return 'hello,World!'

@repair.route('/repair', methods=['POST'])
@auth.login_required
def get_repair():
    infos = Info.query.filter_by(woker_id=None).all()
    return jsonify({'repair': [info.to_json() for info in infos]})

@repair.route('/receive', methods=['POST'])
@auth.login_required
def receive_repair():
    data = request.json
    info = Info.query.get(data['id'])
    info.woker = g.current_user
    db.session.add(info)
    db.session.commit()
    return jsonify({'state':'success'})

@repair.route('/myrepair', methods=['POST'])
@auth.login_required
def my_repair():
    infos = Info.query.filter_by(woker=g.current_user).all()
    return jsonify({'myrepair': [info.to_json() for info in infos]})

@repair.route('/finish', methods=['POST'])
@auth.login_required
def finish_repair():
    data = request.json
    info = Info.query.get(data['id'])
    info.state = 1
    db.session.add(info)
    db.session.commit()
    return jsonify({'state':'success'})

@repair.route('/cancel', methods=['POST'])
@auth.login_required
def cancel_repair():
    data = request.json
    info = Info.query.get(data['id'])
    info.woker = None
    db.session.add(info)
    db.session.commit()
    return jsonify({'state': 'success'})


@repair.route('/distribution', methods=['POST'])
@auth.login_required
def distribution_repair():
    if g.current_user.authorization == 0:
        return unauthorized('Invalid credentials')
    data = request.json
    user = User.query.filter_by(username=data['username']).first()
    info = Info.query.get(data['id'])
    info.woker = user
    db.session.add(info)
    db.session.commit()
    return jsonify({'state': 'success'})

@repair.route('/worker', methods=['POST'])
@auth.login_required
def get_work():
    if g.current_user.authorization == 0:
        return unauthorized('Invalid credentials')
    users = User.query.filter_by(authorization=0).all()
    return jsonify({'woker': [user.to_json() for user in users]})